/*
 * @Author: szx
 * @Date: 2022-03-25 12:42:47
 * @LastEditTime: 2022-03-25 13:00:50
 * @Description:
 * @FilePath: \leetcode\剑指offer\43\43.js
 */
/**
 * @param {number} n
 * @return {number}
 */
var countDigitOne = function (n) {
    let digit = 1; // digit 需为 long 型，因为比如 n 是 INT_MAX，digit 会在最后一次循环越界
    let high = Math.floor(n / 10),
        cur = n % 10,
        low = 0;
    let res = 0;

    while (high != 0 || cur != 0) {
        if (cur == 0) {
            res += high * digit;
        } else if (cur == 1) {
            res += high * digit + low + 1;
        } else {
            res += (high + 1) * digit;
        }

        low += cur * digit;
        cur = high % 10;
        high = Math.floor(high / 10);
        digit *= 10;
    }

    return res;
};
